const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const EvaluationService = require('../../services/good/evaluationService');
class EvaluationController {
    static async getEvaluationList(ctx) {
        // 确保请求体存在，如果不存在则初始化为空对象
        const requestData = ctx.request.body || {};
        
        // 解构分页参数，如果未提供则使用默认值
        const { pageNum = 1, pageSize = 10 } = requestData;
        
        // 创建查询数据对象，排除分页参数
        const queryData = { ...requestData };
        delete queryData.pageNum;
        delete queryData.pageSize;
        
        // 添加用户ID到查询条件中
        queryData.userId = ctx.userId;

        try {
            const res = await EvaluationService.getEvaluationList({ pageNum, pageSize }, queryData);
            response.success(ctx, { data: res });
        } catch (error) {
            response.error(ctx, { message: '获取评价列表失败: ' + error.message });
        }
    }

    static async getEvaluationById(ctx) {
        const { id: evaluationId } = ctx.request.body;
        const res = await EvaluationService.getEvaluationById(evaluationId);

        res ? response.success(ctx, { data: res }) : response.error(ctx, { message: res.msg });
    }

    static async createEvaluation(ctx) {
        var evaluationData = ctx.request.body;

        await EvaluationService.createEvaluation(evaluationData, ctx.userId)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '评价名称重复'));


    }

    static async updateEvaluation(ctx) {
        const evaluationData = ctx.request.body;

        await EvaluationService.updateEvaluation(evaluationData.id, evaluationData.evaluations, ctx.userId)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '评价名称重复'));
    }

    static async deleteEvaluation(ctx) {
        const { id: evaluationId } = ctx.request.body;
        
        try {
            const res = await EvaluationService.deleteEvaluation(evaluationId, ctx.userId);
            if (res) {
                response.success(ctx, { message: '评价删除成功' });
            } else {
                response.error(ctx, { message: '评价删除失败，可能评价不存在或无权限删除' });
            }
        } catch (error) {
            response.error(ctx, { message: '删除评价时发生错误: ' + error.message });
        }
    }
}
module.exports = EvaluationController;